package com.mycase.im.boot.websocket.pattern.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mycase.im.boot.entity.communication.ClientMessage;
import com.mycase.im.boot.entity.communication.ResponseMessage;
import com.mycase.im.boot.entity.database.ImMessage;
import com.mycase.im.boot.service.MessageService;
import com.mycase.im.boot.service.UserService;
import com.mycase.im.boot.websocket.WebSocketSignal;
import com.mycase.im.boot.websocket.pattern.MessageStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.Map;

/**
 * 用来处理好友聊天的场景(单聊)
 * @Author ZhuHJay
 * @Date 2021/9/18 17:42
 */
@Slf4j
@Service
public class FriendChat implements MessageStrategy{

    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;

    @Override
    public Boolean isUse(int type) {
        return WebSocketSignal.MESSAGE_FRIEND == type;
    }

    @Override
    public void executeHandler(ClientMessage clientMessage,
                               ObjectMapper objectMapper,
                               Map<String, Session> clientMaps,
                               Session mySession) throws Exception {
        log.warn("onMessage -匹配到-> FriendChat(好友单聊)");

        // 私聊没有groupId, 以防万一, 进行清空
        clientMessage.setGroupId(null);
        // 判断一下接收人是否存在
        if( !userService.isExist(clientMessage.getToId()) ){
            sendMessage(objectMapper, mySession, ResponseMessage.error("不存在联系人"));
            return;
        }
        // 将发送的信息持久化到数据库中
        // 是否保存成功
        ImMessage imMessage = new ImMessage();
        // 使用浅拷贝赋值对象
        BeanUtils.copyProperties(clientMessage, imMessage);
        if( !messageService.save(imMessage) ){
            sendMessage(objectMapper, mySession, ResponseMessage.error("消息发送失败"));
            return;
        }
        // 将两个自动填充的数据补充上
        imMessage.setNotify(0);
        imMessage.setReadStatus(1);
        // 消息发送
        // 发送给自己
        sendMessage(objectMapper, mySession, ResponseMessage.success()
                    .appendData("type", WebSocketSignal.MESSAGE_FRIEND)
                    .appendData("imMessage", imMessage));
        // 如果好友在线就发送给好友
        if( clientMaps.containsKey(clientMessage.getToId()) ){
            // 消息未读
            imMessage.setReadStatus(0);
            sendMessage(objectMapper, clientMaps.get(clientMessage.getToId()),
                        ResponseMessage.success()
                                .appendData("type", WebSocketSignal.MESSAGE_FRIEND)
                                .appendData("imMessage", imMessage));
        }
    }

}
